﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SGArchiveSystem7xDB.Linq
{
    /// <summary>
    /// 模块操作
    /// </summary>
    public class T_ModelDal
    {
        static SGArchiveSystem7xEntities conn;
        /// <summary>
        /// 添加模块
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static _ReturnValue Add_Model(T_Model en)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                ///同一个PID里的不能有名字重复的模块
                if (conn.T_Model.Select(c => c).Where(c => c.MD_NAME == en.MD_NAME && c.MD_PID == en.MD_PID).Count() > 0)
                    return _ReturnValue.Already;
                else
                {
                    conn.T_Model.Add(en);
                    conn.SaveChanges();
                    return _ReturnValue.OK;
                }
            }
            catch { return _ReturnValue.Err; }
        }
        /// <summary>
        /// 修改模块
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static _ReturnValue Modify_Model(T_Model en)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                ///同一个PID里的不能有名字重复的模块,并且ID号不相同
                if (conn.T_Model.Select(c => c).Where(c => c.MD_ID != en.MD_ID && c.MD_PID == en.MD_PID && c.MD_NAME == en.MD_NAME).Count() > 0)
                    return _ReturnValue.Already;
                else
                {
                    var query = conn.T_Model.Select(c => c).Where(c => c.MD_ID == en.MD_ID);
                    foreach(var n in query)
                    {
                        if (!SGArchiveSystem7xCommons.SGEntity.ModifyEntity(n, en, "MODEL_ID"))
                            return _ReturnValue.Err;
                    }
                    conn.SaveChanges();
                    return _ReturnValue.OK;
                }
            }
            catch { return _ReturnValue.Err; }
        }
        /// <summary>
        /// 获取模块
        /// </summary>
        /// <returns></returns>
        public static List<T_Model> Get_Model(int status=1,int pid=-1)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var query = conn.T_Model.Select(c => c);
                if (status > -1)
                    query = query.Where(c => c.MD_STATUS == status);
                if (pid > -1)
                    query = query.Where(c => c.MD_PID == pid);
                return query.OrderBy(c => c.MD_PID).ThenBy(c => c.MD_ORDER).ToList();
            }
            catch { return null; }
        }
    }
}
